package com.engine.salary.formlua.func.compare;

import com.engine.salary.formlua.core.exception.ErrorType;
import com.engine.salary.formlua.entity.parameter.DataType;
import com.engine.salary.formlua.util.CompareUtil;
import com.engine.salary.formlua.util.DateUtil;
import com.engine.salary.formlua.util.ExcelParamUtil;
import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.instruction.op.OperatorEqualsLessMore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


public class EqOperator extends OperatorEqualsLessMore {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	public EqOperator(String aName) {
		super(aName);
	}

	public EqOperator(String aAliasName, String aName, String aErrorInfo) {
		super(aAliasName, aName, aErrorInfo);
	}

	@Override
	public OperateData executeInner(InstructionSetContext context, ArraySwap list) throws Exception {
		return super.executeInner(context, list);
	}

	@Override
	public Object executeInner(Object... list) throws Exception {
		DataType result=new DataType();
		result.setDataType(DataType.BOOL);
		String oper="=";
		if(list.length!=2){
			throw new RuntimeException("[=]"+ ErrorType.MAX_VAR_COUNT.name());
		}
		Object op1=list[0];
		Object op2=list[1];
		//校验参数类型
		String datatype= ExcelParamUtil.checkParamType(op1);
		String dataType2=ExcelParamUtil.checkParamType(op2);
		if(op2 instanceof Object[]){
			Object[] objectParams=(Object[])op2;
			if(objectParams[0] instanceof DataType){
				DataType paramDataType=(DataType)objectParams[0];
				dataType2=paramDataType.getDataType();
			}else{
				dataType2=ExcelParamUtil.checkParamType(objectParams[0]);
			}
		}

		if(datatype.equals(DataType.OPTION)||dataType2.equals(DataType.OPTION)){
			//对option的特殊处理，获取option的字符串后根据逗号分割，然后排序数组，数组长度不一致返回false，一致则循环对比直到同样下标的数据不一致返回false，否则为true
			try {
				String[] firstOptions=new String[]{};
				String[] secondOptions=new String[]{};
				result.setContent(true);
				firstOptions= CompareUtil.genArray(op1,"option");
				secondOptions=CompareUtil.genArray(op2,"option");
				Arrays.sort(firstOptions);
				Arrays.sort(secondOptions);

//				logger.info("比较选项："+JSON.toJSONString(firstOptions)+"-->"+JSON.toJSONString(secondOptions));
				if(firstOptions.length!=secondOptions.length){
					result.setContent(false);
				}else{
					int i=0;
					for (;i<firstOptions.length;i++){
						boolean loopresult=OperatorEqualsLessMore.executeInner("=",firstOptions[i],secondOptions[i]);
						if(!loopresult){
							result.setContent(false);
							break;
						}
					}
				}
			} catch (Exception e) {
				logger.error("err",e);
				result.setContent(false);
			}
		}else if(op1 instanceof DataType && op2 instanceof DataType && DateUtil.isDateComponent(op1) && DateUtil.isDateComponent(op2)){
			DataType dataTypeOne=(DataType)op1;
			DataType dataTypeTwo=(DataType)op2;
			boolean dateResult=false;
			Date firstDate= DateUtil.buildDateByDateChar(dataTypeOne.getContent()==null?"":dataTypeOne.getContent()+"");
			Date secondDate=DateUtil.buildDateByDateChar(dataTypeTwo.getContent()==null?"":dataTypeTwo.getContent()+"");
			if(firstDate==null || secondDate ==null){
				dateResult= false;
			}else if (firstDate == null && secondDate == null){
				dateResult= true;
			}else{
				dateResult= firstDate.getTime()==secondDate.getTime();
			}
			result.setContent(dateResult);
		}else {
			try {
				List<Object> dataList=ExcelParamUtil.converParamValue(op1,op2);
				if(ExcelParamUtil.getParamType(op1).toLowerCase().equals("double")||ExcelParamUtil.getParamType(op2).toLowerCase().equals("double")){
					boolean r=OperatorEqualsLessMore.executeInner("=",ExcelParamUtil.convertParamValToNumber(dataList.get(0)),ExcelParamUtil.convertParamValToNumber(dataList.get(1)));
					result.setContent(r);
				}else if(op1 instanceof DataType && op2 instanceof DataType && DateUtil.isDateComponent(op1) && DateUtil.isDateComponent(op2)){


					Object dateStringOne=null;
					if(op1 instanceof DataType){
						DataType dataTypeOne=(DataType)op1;
						dateStringOne=dataTypeOne.getContent();
					}else{
						dateStringOne=op1;
					}

					Object dateStringTwo=null;
					if(op2 instanceof DataType){
						DataType dataTypeTwo=(DataType)op2;
						dateStringTwo=dataTypeTwo.getContent();
					}else{
						dateStringTwo=op2;
					}
					boolean dateResult=false;
					Date firstDate=DateUtil.buildDateByDateChar(dateStringOne==null?"":dateStringOne+"");
					Date secondDate= DateUtil.buildDateByDateChar(dateStringTwo==null?"":dateStringTwo+"");
					if (firstDate == null && secondDate == null){
						dateResult= true;
					}else if(firstDate==null || secondDate ==null){
						dateResult= false;
					}else{
						dateResult= firstDate.getTime()==secondDate.getTime();
					}
					result.setContent(dateResult);
				}else {
					Object firstParam=ExcelParamUtil.getParamContent(dataList.get(0),"");
					Object secondParam=ExcelParamUtil.getParamContent(dataList.get(1),"");
					if((firstParam instanceof String || firstParam instanceof Character) && (secondParam instanceof String || secondParam instanceof Character)){
						if(firstParam.toString().length()==1&&secondParam.toString().length()==1){
							boolean r=firstParam.toString().equals(secondParam.toString());
							result.setContent(r);
							return result;
						}
					}
					boolean r=OperatorEqualsLessMore.executeInner("=",firstParam,secondParam);
					result.setContent(r);
				}
			} catch (Exception e) {
				logger.error("err",e);
			}
		}
//		buildFilterParam(result,op1,op2);
		return result.getContent();
	}

	/**
	 * 构建搜索条件参数
	 * @param dataType
	 * @param obj1
	 * @param obj2
	 */
//	private void buildFilterParam(DataType dataType,Object obj1,Object obj2){
//		List<FormulaFilterData> filterFormDataList=new ArrayList<>();
//		FormulaFilterData filterData=new FormulaFilterData();
//		String content = null;
//		try {
//			if(obj1!=null && (obj1 instanceof DataType)){
//				DataType dataType1=(DataType)obj1;
//				if(StringUtils.isEmpty(dataType1.getComponentKey())){
//					dataType1.setComponentKey(dataType1.getDataType());
//				}
//				if(obj2 instanceof DataType) {
////					content = ((DataType) obj2).getContent()+"";
//					DataType paramDataType=(DataType) obj2;
//					if(paramDataType==null || paramDataType.getContent() == null){
//						content = "";
//					}else{
//						content = paramDataType.getContent()+"";
//					}
//				}else {
//					content =  obj2+"";
//				}
//				if ( content != null) {
//					filterData.setFieldId(dataType1.getFieldId());
//					if(dataType1.getSubFormId() != null) {
//						filterData.setSubFormId(dataType1.getSubFormId()+"");
//					}
//
//					filterData.setComponentKey(dataType1.getComponentKey());
//					if(StringUtils.isEmpty(content)) {
//						filterData.setTerm(FilterFormData.TERM_NULL);
//					}else{
//						filterData.setTerm(FilterFormData.TERM_EQ);
//						if(StringUtils.isNotEmpty(dataType1.getComponentKey())){
//							//数字类型
//							if(ComponentConfig.isNumberComponent(dataType1.getComponentKey())
//									|| dataType1.getComponentKey().equals(ComponentType.DateComponent.toString())
//									|| dataType1.getComponentKey().equals(ComponentType.TimeComponent.toString())
//									|| dataType1.getComponentKey().equalsIgnoreCase(DataType.STRING)
//									|| dataType1.getComponentKey().equalsIgnoreCase(DataType.NUMBER)||
//									dataType1.getComponentKey().equalsIgnoreCase(DataType.DATE)
//									|| dataType1.getComponentKey().equalsIgnoreCase(DataType.BOOL)
//							) {
//								filterData.setContent(content);
//								//选项控件
//							}else if(ComponentConfig.isOptionComponent(dataType1.getComponentKey())) {
//								List<String> ids = new ArrayList<>();
//								String[] idsArray = content.split(",");
//								for(String idStr : idsArray) {
//									if(StringUtils.isNotBlank(idStr)) {
//										ids.add(idStr);
//									}
//								}
//								filterData.setIds(ids);
//								//文本型
//							}else {
//								filterData.setContent(content);
//							}
//						}
//
//					}
//				}
//				if(filterData!=null){
//					filterFormDataList.add(filterData);
//				}
//
//				logger.info("=号构建过滤参数："+(filterFormDataList!=null? JSON.toJSONString(filterFormDataList):"NULL"));
//				dataType.setFormulaFilterDataList(filterFormDataList);
//				dataType.setComponentKey(dataType1.getComponentKey());
//				dataType.setSubFormId(dataType1.getSubFormId());
//			}
//		} catch (Exception e) {
//			logger.error("err",e);
//		}
//
//	}


}
